/**
 * 主功能页面，用于设置行业
 * author:mengxn
 * date:2016年8月23日3:18:42
 */

var saveImgPK = "";
var deleImgPK = "";
var kmMaintanceUpdate = {
    onlike: function () {
        $("#like").click(function () {
            layer.config({
                extend: 'skin/layer.css'
            });
            layer.open({
                type: 2,
                title: false,
                shade: [0],
                area: ['1000px', '580px'],
                shift: 2,
                content: ['html/bdIndustryChart.html'], //iframe的url，no代表不显示滚动条
            });
        });
    },

    //知识类别查所有
    initAll: function () {
        common.showLoading();
        var pk_user = window.localStorage.userid;
        var url = "/PCKnowledgeCategoryEntity/getKnowledgeCategoryByCondition";
        map = {"level": 1, "fw_parent": '', "pk_user": pk_user}
        common.interfaceAjaxFunction(url, map, this.showLeftPartTreeSuccess);
    },
    showLeftPartTreeSuccess: function (json) {
        //成功时候
        if (json.status == "0") {
            if (json.data.length > 0) {
                var jsonData = json.data;
                var obj = $("#addSelect");
                for (var i = 0; i < jsonData.length; i++) {
                    obj.append("<option value='" + jsonData[i].pk_knowledge_category + "'   >" + jsonData[i].knowledge_category_name + "</option>");
                }

            } else {
                //加载设置页面
                layer.msg("当前无行业树结构数据，请联系管理员维护");
            }
            //初始化其他数据
            kmMaintanceUpdate.init();
        } else {
            //给出信息提示
            layer.msg(json.message);
        }
        //转圈提示去除
        //common.hideLoading();
    },

    pageSelect: function (json) {
        var obj = $("#appendSele");
        var ht = "";
        obj.html("<option value=''>--请选择类别--</option>");
        if (json.status == "0") {
            if (json.data.length > 0) {
                var jsonData = json.data;

                for (var i = 0; i < jsonData.length; i++) {
                    ht += "<option value='" + jsonData[i].pk_knowledge_category + "' >" + jsonData[i].knowledge_category_name + "</option>";
                }
                obj.append(ht);

            } else {
                //加载设置页面
                //layer.msg("当前无行业树结构数据，请联系管理员维护");
            }
        } else {
            //给出信息提示
            layer.msg(json.message);
        }
        //转圈提示去除
        //common.hideLoading();
    },

    //初始查询当前ID 知识信息
    init: function () {
        var url = "/kmpublish/App/queryKnowledgeAttByPK";
        var id = window.sessionStorage.AllId;
        var pk_user = window.localStorage.userid;
        map = {"pk_publish": id, "pk_user": pk_user};
        common.interfaceAjaxFunction(url, map, this.initFz);
    },
    initFz: function (json) {
        if (json.status == "0") {
            if (typeof(json.data[0]) != "undefined") {
                //给页面 元素赋值
                var obj = json.data[0];
                var select = $("#addSelect").children("option");
                for (var i = 0; i < select.length; i++) {
                    if (select[i].text == obj.km_type_name) {
                        select[i].selected = 'selected';
                    }
                }
                var obj1 = json.data1;

                var app = $("#appendSele");
                app.html("<option value=''>--请选择类别--</option>");
                if (typeof(obj1) != "undefined" && obj1 != null) {
                    for (var i = 0; i < obj1.length; i++) {
                        app.append("<option value='" + obj1[i].pk_knowledge_category + "' >" + obj1[i].knowledge_category_name + "</option>");
                    }

                    var select1 = $("#appendSele").children("option");
                    for (var i = 0; i < select1.length; i++) {
                        if (select1[i].text == obj.km_type_name2) {
                            select1[i].selected = 'selected';
                        }
                    }
                }

                $("#pk_publish_user").html(obj.publish_user_name);
                $("#publish_time").html("发布日期     " + obj.publish_time);
                $("#publish_title").val(obj.publish_title);
                $("#publish_memo").val(obj.publish_memo);
                $("#publish_key").val(obj.publish_key);
                $("#pk_km_publish").val(obj.pk_km_publish);
                if (obj.studioUrl != undefined && obj.studioUrl != '' && obj.studioUrl != null) {
                    var studioUrlList = obj.studioUrl.split(',');
                    for (var i = 0; i < studioUrlList.length; i++) {
                        if (i == studioUrlList.length - 1) {
                            $("#add_studio_url").prev().val(studioUrlList[i]);
                        } else {
                            var urlHtml = '<input type="text" value="'+studioUrlList[i]+'"  class="studio_url" maxlength="200"/><span class="del_studio_url" style="color: red">删除</span>';
                            $("#add_studio_url").prev().before(urlHtml);
                            //删除视频地址按钮
                            $(".del_studio_url").unbind().on("click", function () {
                                $(this).prev().remove();
                                $(this).remove();
                            });
                        }
                    }

                }

                if (typeof(json.data[0].achementList_pic) != "undefined") {

                    for (var j = 0; j < obj.achementList_pic.length; j++) {
                        if (obj.achementList_pic[j].upload_type == '0') {
                            if (obj.achementList_pic[j].fileurl != null)
                            //$("#img").append("<div class='updaimg-img'><img src='"+obj.achementList_pic[j].fileurl+"' alt=''/><div class='upda-closed onUpdateimg' imgUpdateId='"+obj.achementList_pic[j].pk_attachment+"'></div></div>")
                                kmMaintanceUpdate.picDownload(obj.achementList_pic[j].pk_attachment);
                        } else {
                            if (obj.achementList_pic[j].fileurl != null)
                                $("#pdf").append("<div><p ><a href='" + obj.achementList_pic[j].fileurl + "'>下载</a>&nbsp;&nbsp;&nbsp;&nbsp;" + obj.achementList_pic[j].fname + "<span>" + obj.achementList_pic[j].filesize + "</span><span class='glyphicon glyphicon-remove onUpdateimg' style='cursor:pointer;' imgUpdateId='" + obj.achementList_pic[j].pk_attachment + "'></span></p></div>")
                        }

                    }

                }
                if (typeof(json.data[0].achementList_oth) != "undefined") {
                    for (var j = 0; j < obj.achementList_oth.length; j++) {
                        if (obj.achementList_oth[j].upload_type != '0') {
                            if (obj.achementList_oth[j].fileurl != null)
                                $("#pdf").append("<div><p ><a href='" + obj.achementList_oth[j].fileurl + "'>下载</a>&nbsp;&nbsp;&nbsp;&nbsp;" + obj.achementList_oth[j].fname + "<span>" + obj.achementList_oth[j].filesize + "</span><span class='glyphicon glyphicon-remove onUpdateimg' style='cursor:pointer;' imgUpdateId='" + obj.achementList_oth[j].pk_attachment + "'></span></p></div>")
                        }
                    }
                }


                $(".onUpdateimg").unbind().on("click", function () {
                    $(this).parent().remove();
                    var del_id = $(this).attr("imgUpdateId");
                    deleImgPK += del_id + ",";
                    var url = "/file/delFile";
                    map = {
                        "pk_att": del_id
                    }
                    common.interfaceAjaxFunction(url, map, kmMaintanceUpdate.delPage);
                });


            } else {
                //加载设置页面
                layer.msg("当前无行业树结构数据，请联系管理员维护");
            }
        } else {
            //给出信息提示
            layer.msg(json.message);
        }
        //转圈提示去除
        common.hideLoading();
    },
    /**
     * 图片的异步取得
     */
    picDownload: function (filePk) {
        //请求参数
        var url = "/file/picdownload/" + filePk;
        common.interfaceAjaxFunction(url, "", kmMaintanceUpdate.picDownloadSuccess, true, filePk, false);
    },
    /**
     * 下载成功
     */
    picDownloadSuccess: function (res, filePk) {
        $("#img").append("<div class='updaimg-img'><img src='data:image/png;base64," + res + "' alt=''/><div class='upda-closed onUpdateimg' imgUpdateId='" + filePk + "'></div></div>")
        //图片预览
        layer.ready(function () { //为了layer.ext.js加载完毕再执行
            layer.photos({
                photos: '.updaimg'
            });
        });

        $(".onUpdateimg").unbind().on("click", function () {
            $(this).parent().remove();
            var del_id = $(this).attr("imgUpdateId");
            deleImgPK += del_id + ",";
            var url = "/file/delFile";
            map = {
                "pk_att": del_id
            }
            common.interfaceAjaxFunction(url, map, kmMaintanceUpdate.delPage);
        });

    },
    //绑定事件  修改
    bindEvent: function () {

        // 新增视频地址按钮
        $("#add_studio_url").unbind().on("click", function () {
            var urlHtml='<span class="del_studio_url" style="color: red">删除</span><input type="text"   class="studio_url" maxlength="200"/>';
            $(this).before(urlHtml);
            //删除视频地址按钮
            $(".del_studio_url").unbind().on("click", function () {
                $(this).prev().remove();
                $(this).remove();
            });
        });

        $("#fabuton").unbind().on("click", function () {
            var pk_publish_user = $("#pk_publish_user").html();
            var publish_time = $("#publish_time").html();
            var publish_title = $("#publish_title").val();
            var publish_memo = $("#publish_memo").val();
            var publish_key = $("#publish_key").val();
            var pk_km_publish = $("#pk_km_publish").val();
            var files_new = saveImgPK.substring(0, saveImgPK.length - 1);
            var files_del = deleImgPK.substring(0, deleImgPK.length - 1);
            var pk_knowledge = jQuery("#addSelect").val();
            var pk_category = jQuery("#appendSele").val();
            var studio_url_list=$(".knowledgeStudiourl input");
            var studio_url='';
            if(studio_url_list!=null&&studio_url_list!=''&&studio_url_list!=undefined){
                var urlTemp='';
                for(var i=0;i<studio_url_list.length;i++){
                    urlTemp=studio_url_list[i].value;
                    if(urlTemp!=null&&urlTemp.trim()!=''){
                        studio_url+=urlTemp+',';
                    }
                }
                if(studio_url.charAt(studio_url.length-1)==','){
                    studio_url=studio_url.substr(0,studio_url.length-1);
                }
            }

            if (pk_knowledge !== null || pk_knowledge !== undefined || pk_knowledge !== '') {
                pk_knowledge_category = pk_knowledge;
            }
            if (pk_category === '') {

            } else {
                pk_knowledge_category = pk_category;
            }


            if (publish_title === '') {
                layer.msg('请填写商品名称');
                return;
            }
            if (publish_memo === '') {
                layer.msg('请填写商品简介');
                return;
            }
            if (publish_key === '') {
                layer.msg('请至少选择一个关键字');
                return;
            }
            if (publish_memo === '') {
                layer.msg('请填写规格');
                return;
            }
            var name1 = [];
            name1 = publish_key.split(",");
            if (name1.length > 20) {
                layer.msg('最多选择20个关键字');
                return;
            }

            if (pk_knowledge_category === '') {
                layer.msg('请选择商品类别！');
                return;
            }
            map = {
                "pk_publish_user": pk_publish_user,
                "publish_time": publish_time,
                "publish_memo": publish_memo,
                "publish_key": publish_key,
                "pk_km_publish": pk_km_publish,
                "studio_url": studio_url,
                "km_type": pk_knowledge_category,
                "publish_title": publish_title,
                "files_new": files_new,
                "files_del": files_del
            }
            var url = "/PCpublish/updatePublishEntity";
            common.interfaceAjaxFunction(url, map, kmMaintanceUpdate.initPage);
        });
        // 取消按钮
        $("#cancle-product").unbind().on("click", function () {
            common.loadPageDiv("html/kmMaintance.html");
        });

    },
    initPage: function (json) {
        if (json.status == "0") {
            if (json.message == "数据修改成功!") {
                layer.msg("修改成功!");
                common.loadPageDiv("html/kmMaintance.html");
            }
        }
    },
    delPage: function (json) {
        if (json.status == "0") {
            layer.msg(json.message);
        }

    },
    initialize: function () {
        common.showLoading();
        //初始化
        saveImgPK = "";
        deleImgPK = "";

        kmMaintanceUpdate.initAll();
        kmMaintanceUpdate.onlike();
        kmMaintanceUpdate.bindEvent();

        var html = "";
        var pdf = "";
        $('#file_upload').Huploadify({
            'uploader': '/shellkm/file/uploadFile',
            'height': 25,
            'whith': 120,
            'auto': true,
            'fileDataName': 'file',
            'buttonText': '选择文件...',
            'fileTypeExts': '*.doc; *.docx;  *.xls; *.xlsx; *.ppt; *.pptx; *.pdf; *.jpg; *.jpeg; *.tiff; *.bmp; *.gif; *.mp4; *.png',
            'multi': true,
            'method': 'post',
            'debug': false,
            'simUploadLimit': 6,
            'onUploadSuccess': function (file, data, response) {

                var obj = jQuery.parseJSON(data);
                //console.log(JSON.stringify(obj))
                if (obj.data.file_type == '0') {
                    html = "<div class='updaimg-img'><img src='data:image/png;base64," + obj.data.pic_string + "' alt='' widht='200' height='200'/><div class='upda-closed onimg' imgId='" + obj.data.pk_att + "'></div></div>";
                    $("#img").append(html);
                } else {

                    pdf = "<div><p><a href='" + obj.data.file_url + "'>下载</a>&nbsp;&nbsp;&nbsp;&nbsp;" + obj.data.file_name + "<span>" + obj.data.file_size + " </span><span class='glyphicon glyphicon-remove onimg' imgId='" + obj.data.pk_att + "'></span></p></div>";
                    $("#pdf").append(pdf);
                }

                $(".onimg").unbind().on("click", function () {
                    $(this).parent().remove();
                    var del_id = $(this).attr("imgId");
                    deleImgPK += del_id + ",";
                    var url = "/file/delFile";
                    map = {
                        "pk_att": del_id
                    }
                    common.interfaceAjaxFunction(url, map, kmMaintanceUpdate.delPage);
                });
                saveImgPK += obj.data.pk_att + ",";
            },
            'onUploadError': function (file, errorCode, errorMsg, errorString) {

            }
        });

        $("#addSelect").change(function () {
            var LTId = this.value;
            var url = "/PCKnowledgeCategoryEntity/getKnowledgeCategoryByCondition";
            map = {"level": 2, "fw_parent": LTId, "pk_user": window.localStorage.userid}
            common.interfaceAjaxFunction(url, map, kmMaintanceUpdate.pageSelect);
        });

    }


};
